package com.cyh.core.login.controller;

import com.cyh.core.framework.annotation.OperationLogDetail;
import com.cyh.core.framework.annotation.PassToken;
import com.cyh.core.framework.annotation.RoleToken;
import com.cyh.core.framework.annotation.UserLoginToken;
import com.cyh.core.framework.domain.dto.ResultDTO;
import com.cyh.core.framework.domain.dto.SimplePageDTO;
import com.cyh.core.framework.domain.dto.SimpleQueryDTO;
import com.cyh.core.login.entity.User;
import com.cyh.core.login.entity.UserInfo;
import com.cyh.core.login.service.user.IUserInfoService;
import com.cyh.core.login.service.user.IUserService;
import com.cyh.core.framework.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${server.servlet.context-path}")
    String contextPath;

    @Autowired
    IUserService iUserService;

    @Autowired
    IUserInfoService userInfoService;

    @PassToken
    @PostMapping("/login")
    public ResultDTO login(User user, HttpServletRequest httpServletRequest, HttpServletResponse response) {

        Cookie []cookies= httpServletRequest.getCookies();
        if(cookies!=null) {
            for (Cookie coo : cookies) {
                if (coo.getName().equals("token")) {
                    return ResultDTO.Success("存在token，无需登陆");
                }
            }
        }
        user.setTempObject(response);
        return iUserService.userLogin(user);
    }

    @UserLoginToken
    @RequestMapping("/logout")
    @OperationLogDetail
    public ResultDTO logout(HttpServletResponse response, HttpServletRequest httpServletRequest){
        String token=JWTUtil.getTokenFromHTTP(httpServletRequest);
        if(iUserService.userLogOut(token)) {
            Cookie cookie = new Cookie("token", "");
            cookie.setMaxAge(0);
            cookie.setPath(contextPath);
            response.addCookie(cookie);
            return ResultDTO.Success( "Logout OK!");
        }else {
            return ResultDTO.Failure(500, "Logout Error!");
        }
    }

    @RoleToken(Roleid = {0,1})
    @PostMapping("/create")
    @OperationLogDetail(level = 2)
    public ResultDTO create(User user){
        return iUserService.userCreate(user);
    }

    @RoleToken(Roleid = {0,1,2})
    @PostMapping("/update")
    @OperationLogDetail(level = 2)
    public ResultDTO update(@RequestParam(value = "oldPassword",required = true)String oldPassword,
                                User user,HttpServletRequest httpServletRequest, HttpServletResponse response){

        if( user.getPassword()==null || oldPassword==null) {
            return ResultDTO.Failure(403,"请完整输入密码参数!");
        }
        HashMap<String,Object> map=new HashMap<>();
        map.put("oldPassword",oldPassword);
        //map.put("response",response);
        map.put("token",JWTUtil.getTokenFromHTTP(httpServletRequest));
        user.setTempObject(map);
        ResultDTO dto=iUserService.userUpdate(user);
        if (dto.isSuccess() && dto.getData() instanceof User){
            Cookie cookie = new Cookie("token", "");
            cookie.setMaxAge(0);
            cookie.setPath(contextPath);
            response.addCookie(cookie);
            user.setPassword(null);
        }
        if(dto.isSuccess())dto.setCount(1);
        return dto;
    }

    @RoleToken(Roleid = {0,1})
    @GetMapping("/advancedSearch")
    @OperationLogDetail
    public ResultDTO advancedSearch(@RequestBody Map<String,Object> map) throws Exception {
        SimplePageDTO pageDTO=BeanMapUtil.mapsToObject((Map<String, Object>) map.get("pageDTO"),SimplePageDTO.class);
        Map<String,Object> queryCondition=(Map<String, Object>)map.get("queryCondition");
        pageDTO.Check();
        SimpleQueryDTO simpleQueryDTO=new SimpleQueryDTO(pageDTO,queryCondition);
        List<User> users=iUserService.advancedSearch(simpleQueryDTO);
        return ResultDTO.Success(users);
    }


    @UserLoginToken
    @GetMapping("/getUserInfo")
    @OperationLogDetail
    public ResultDTO getUserInfo(){
        User user=iUserService.getCurrentUser();
        return ResultDTO.Success("当前用户详情",userInfoService.getUserInfoByUid(user.getId()));
    }

    @RoleToken(Roleid = {0,1})
    @GetMapping("/getUserInfo/{id}")
    @OperationLogDetail
    public ResultDTO getUserInfo(@PathVariable(name = "id",required = true) Integer ID){
        UserInfo userInfo=null;
        if( ID.intValue() >= 0 ) {
            userInfo=userInfoService.getUserInfoByUid(ID);
            if (userInfo!=null) {
                return ResultDTO.Success("管理员获取id: " + ID.intValue() + " 用户详情", userInfo);
            }else {
                return ResultDTO.Failure(403,"id: "+ID+" 用户不存在");
            }
        } else {
          return ResultDTO.Failure(403,"id不为负数");
        }
    }

    @UserLoginToken
    @PostMapping("/updateUserInfo")
    @OperationLogDetail(level = 2)
    public ResultDTO updateUserInfo(UserInfo userInfo){
        User user=iUserService.getCurrentUser();
        boolean isok=false;
        if("男".equals(userInfo.getSex())||"女".equals(userInfo.getSex())){
            if(userInfo.getDetail()!=null && !userInfo.getDetail().equals("")){
                if(userInfo.getBirthday()!=null){
                    isok=true;
                }
            }
        }
        if(!isok){
            return ResultDTO.Failure(403,"请正确填写信息!");
        }
        try {
            userInfo.setUid(user.getId());
            userInfoService.updateUserInfo(userInfo);
            return ResultDTO.Success();
        }catch (Exception e){
            return ResultDTO.Failure(500,e.getMessage());
        }
    }

}
